<template>
  <div class="insured-management">
    <el-card class="page-container">
      <template #header>
        <div class="card-header">
          <span>参合信息录入</span>
          <el-button type="primary" @click="handleAddInsured">新增参合人</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-input
          v-model="searchQuery"
          placeholder="请输入姓名或身份证号搜索"
          style="width: 300px"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 参合人信息表格 -->
      <el-table :data="filteredInsuredList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="insuredName" label="姓名" width="120" />
        <el-table-column prop="caardId" label="身份证号" width="180" />
        <el-table-column prop="gender" label="性别" width="80" />
        <el-table-column prop="nation" label="民族" width="100" />
        <el-table-column prop="address" label="地址" min-width="200" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑参合人对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑参合人信息' : '新增参合人'"
        width="40%"
    >
      <el-form :model="currentInsured" label-width="100px" :rules="rules" ref="insuredForm">
        <el-form-item label="姓名" prop="insuredName">
          <el-input v-model="currentInsured.insuredName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="caardId">
          <el-input v-model="currentInsured.caardId" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="currentInsured.gender" placeholder="请选择性别" style="width: 100%">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="民族" prop="nation">
          <el-select v-model="currentInsured.nation" placeholder="请选择民族" style="width: 100%">
            <el-option v-for="nation in nations" :key="nation" :label="nation" :value="nation" />
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="currentInsured.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="currentInsured.phone" placeholder="请输入联系电话" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitInsured">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'

// 民族列表
const nations = [
  '汉族', '蒙古族', '回族', '藏族', '维吾尔族', '苗族', '彝族', '壮族', '布依族', '朝鲜族',
  '满族', '侗族', '瑶族', '白族', '土家族', '哈尼族', '哈萨克族', '傣族', '黎族', '傈僳族'
]

// 表单验证规则
const rules = {
  insuredName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  caardId: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  nation: [
    { required: true, message: '请选择民族', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' },
    { min: 5, max: 50, message: '长度在 5 到 50 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const insuredList = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const searchQuery = ref('')
const insuredForm = ref(null)

const currentInsured = ref({
  id: 0,
  insuredName: '',
  caardId: '',
  gender: '',
  nation: '',
  address: '',
  phone: ''
})

// 加载参合人列表（带模糊查询）
const loadInsuredList = async () => {
  const res = await axios.get('/insured/list', {
    params: { keyword: searchQuery.value }
  })
  if (res.data.code === 200) {
    insuredList.value = res.data.data
  }
}

// 过滤后的参合人列表（前端过滤已由后端接口替代）
const filteredInsuredList = computed(() => insuredList.value)

// 初始化数据
onMounted(() => {
  loadInsuredList()
})

// 搜索监听
watch(searchQuery, () => {
  loadInsuredList()
})

// 处理添加参合人
const handleAddInsured = () => {
  isEdit.value = false
  currentInsured.value = {
    id: 0,
    insuredName: '',
    caardId: '',
    gender: '',
    nation: '',
    address: '',
    phone: ''
  }
  dialogVisible.value = true
}

// 处理编辑参合人
const handleEdit = (index, row) => {
  isEdit.value = true
  currentInsured.value = { ...row }
  dialogVisible.value = true
}

// 处理删除参合人
const handleDelete = (index, row) => {
  ElMessageBox.confirm('确认删除该参合人信息吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await axios.delete(`/insured/delete/${row.id}`)
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        loadInsuredList()
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 提交参合人信息
const submitInsured = () => {
  if (!insuredForm.value) return
  insuredForm.value.validate(async (valid) => {
    if (valid) {
      let res
      if (isEdit.value) {
        res = await axios.put('/insured/update', currentInsured.value)
      } else {
        res = await axios.post('/insured/add', currentInsured.value)
      }
      if (res.data.code === 200) {
        ElMessage.success(isEdit.value ? '参合人信息更新成功' : '参合人添加成功')
        dialogVisible.value = false
        loadInsuredList()
      } else {
        ElMessage.error(res.data.message || '操作失败')
      }
    }
  })
}
</script>

<style scoped>
.insured-management {
  padding: 20px;
}

.page-container {
  margin: 0;
  min-height: calc(100vh - 140px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.search-area {
  margin-bottom: 20px;
}

.el-table {
  margin-top: 20px;
}
</style>